/**   
* @Title: DynamicDataSourceAspect.java
* @Package org.xaoyaoyao.cloud.dynamic.aop
* @Description: TODO
* @author xaoyaoyao
* @date Jul 3, 2019 3:38:14 PM
* @version V1.0   
*/
package org.xaoyaoyao.cloud.dynamic.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.xaoyaoyao.cloud.dynamic.annotation.DynamicDataSource;
import org.xaoyaoyao.cloud.dynamic.source.DynamicDataSourceContextHolder;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: DynamicDataSourceAspect
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jul 3, 2019 3:38:14 PM
 * 
 */
@Slf4j
public class DynamicDataSourceAspect {

	@Before("@annotation(ds)")
	public void changeDataSource(JoinPoint point, DynamicDataSource ds) throws Throwable {
		String dsId = ds.value();
		if (DynamicDataSourceContextHolder.dataSourceIds.contains(dsId)) {
			if (log.isDebugEnabled()) {
				log.debug(">>>>>>>> Use DataSource :{} >", dsId, point.getSignature());
			}
		} else {
			if (log.isInfoEnabled()) {
				log.info(">>>>>>>> 数据源[{}]不存在，使用默认数据源 >{}", dsId, point.getSignature());
			}
			DynamicDataSourceContextHolder.setDataSourceRouterKey(dsId);
		}
	}

	@After("@annotation(ds)")
	public void restoreDataSource(JoinPoint point, DynamicDataSource ds) {
		if (log.isDebugEnabled()) {
			log.debug(">>>>>>>> Revert DataSource : " + ds.value() + " > " + point.getSignature());
		}
		DynamicDataSourceContextHolder.removeDataSourceRouterKey();
	}

}
